package com.sui.bigdata.rtcadmin.async;


import com.sui.bigdata.rtcadmin.constant.AppConstant;
import com.sui.bigdata.rtcadmin.model.dto.SparkAppDto;
import com.sui.bigdata.rtcadmin.repository.model.SparkApp;
import com.sui.bigdata.rtcadmin.util.RedisUtils;
import com.sui.bigdata.rtcadmin.util.SendMsgUtils;
import com.sui.bigdata.rtcadmin.util.SparkAlarmUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: TingWuHuang
 * @Date: 2020/5/6 15:30
 * @description
 */
@Component
public class SparkAppAlarm implements Runnable{

    Logger logger = LoggerFactory.getLogger(SparkAppAlarm.class);

    @Value("${oneday.max.restart.time}")
    private Integer onedayMaxRestartTime;

    @Value("${alarm.msg.url}")
    private String alarmMsgUrl;

    private final Long ttl = 24 * 60 * 60L;

    private String ID = "APP";

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private SparkAlarmUtil alarmUtil;

    private SparkApp sparkApp;
    private String appStatus;


    public void setSparkApp(SparkApp sparkApp) {
        this.sparkApp = sparkApp;
    }
    public void setAppStatus(String appStatus) {
        this.appStatus = appStatus;
    }

    public static SparkAppAlarm build(SparkAppAlarm sparkAppAlarm, SparkApp sparkApp, String appStatus){
        sparkAppAlarm.setAppStatus(appStatus);
        sparkAppAlarm.setSparkApp(sparkApp);
        return sparkAppAlarm;
    }

    @Override
    public void run() {

        if (StringUtils.isNotBlank(sparkApp.getAlarmGroupPhone())) {
            alarmMsgUrl = alarmMsgUrl + sparkApp.getAlarmGroupPhone();
        }
        String lockKey = sparkApp.getAppName() + "_restart";
        String lockValue = UUID.randomUUID().toString();
        try {
            if (redisUtils.setScheduler(lockKey, lockValue, 61)) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                String todayDate = formatter.format(new Date(System.currentTimeMillis()));

                String appName = sparkApp.getAppName();
                String key = ID + appName + todayDate;
                Integer todayRestartTimes = redisUtils.getInteger(key);

                if (todayRestartTimes < onedayMaxRestartTime) {
                    alarmUtil.restartJob(appName, alarmMsgUrl,sparkApp, AppConstant.WEB_PREFIX +
                            sparkApp.getAppId() + AppConstant.WEB_SUFFIX, appStatus);
                    redisUtils.set(key, todayRestartTimes + 1, ttl);
                    logger.warn("{} was restarted for the {} time today", appName, todayRestartTimes + 1);
                } else {
                    logger.warn("{} has restarted 3 times.", appName);
                    SendMsgUtils.sendSparkAppRestartFailMsg(alarmMsgUrl, appName, sparkApp.getDeveloper(), appStatus,
                            AppConstant.WEB_PREFIX + sparkApp.getAppId() + AppConstant.WEB_SUFFIX);
                }
            }
        } catch (Exception e) {
            logger.error("restartTask {} exception.", sparkApp.getAppName(), e);
        }

    }


}
